﻿// Apache-2.0 License
// Copyright (c) 2021-2022 SuperJeff
// 微信:15906588664  QQ:1024489

using Admin.Net.InformationPlatform.Entity;
using Admin.Net.InformationPlatform.Service.SRM.Dto;
using Admin.NET.Application.Const;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using FluentFTP;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;

using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nest;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinUserInfoBatchGetRequest.Types;

namespace Admin.Net.InformationPlatform.Service.SRM
{
    /// <summary>
    /// SRM管理
    /// </summary>
    [ApiDescriptionSettings(groups: "SRM", Name = "采购管理", Tag = "采购管理", Order = 200)]

    public class SrmPurchaseService : IDynamicApiController, ITransient
    {
        private readonly SysUserRoleService _sysUserRoleService;
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _Dilon;

        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;


        /// <summary>
        /// srm采购管理模块
        /// </summary>
        /// <param name="db"></param>
        public SrmPurchaseService(ISqlSugarClient db, SysUserRoleService sysUserRoleService)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);

            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db,_Dilon);

            _sysUserRoleService = sysUserRoleService;
        }


        /// <summary>
        /// 获取采购需求清单-分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/GetPurchasePagedList")]
        public async Task<SqlSugarPagedList<GetSrmPurchaseOutput>> GetPurchasePagedList(SrmPurchaseInput input)
        {
            // // 角色信息
            // var roles = await _sysUserRoleService.GetUserRoleList( _User.ID.ToLong());
            //var  LoginRole = roles.Select(u => new LoginRole
            // {
            //     Name = u.Name,
            //     Code = u.Code
            // }).ToList();
            // int role = LoginRole.Where(u => u.Code == "All_Data").Count();//判断是否拥有全部数据角色
           // var rolecount = _SjDb.Queryable<SRMCG>().Where(c => c.SRMCGRID == "020521" ).ToList();//查看用户是否拥有查看全部数据的角色

            if (input.PageSize == 0)
            {
                input.PageSize = 100;
            }
            //List<GetSrmPurchaseOutput> output = new List<GetSrmPurchaseOutput>();
            var output = await _SjDb.Queryable<SRMCG>().AS("SJADMIN.SRMCG")

                .LeftJoin<SRMCG_LIST>((b, l) => (b.SRMCGID == l.SRMCG_ID))
                .Where(b => b.SRMISDELETE == 0)
                .Where((b, l) => (l.SRMISDELETE == 0))
                .WhereIF(_User.RoleList==false, b => b.SRMCGRID == _User.UserId)//采购员为当前登录人
                .WhereIF(input.EndDate != null, (b, l) => (l.SRMCREATE <= input.EndDate)) //结束日期
                .WhereIF(input.StartDate != null, (b, l) => (l.SRMCREATE >= input.StartDate)) //开始日期
                .WhereIF(!string.IsNullOrEmpty(input.ProductNo), (b, l) => (l.SRMPM.Contains(input.ProductNo))) //品号
                .WhereIF(!string.IsNullOrEmpty(input.ProductName), (b, l) => (l.SRMPH.Contains(input.ProductName))) //品名
                .WhereIF(!string.IsNullOrEmpty(input.ProductSpecifications), (b, l) => (l.SRMGG.Contains(input.ProductSpecifications))) //规格
                .OrderBy(b => b.SRMCREATE) //采购单日期排序
                .Select((b, l) => new GetSrmPurchaseOutput
                {
                    SRMCGRID = b.SRMCGRID,
                    //SRMCGRNAME = _User.RealName,
                    SRMCGRNAME =b.SRMCGRNAME,//采购员姓名
                    SRMCGID = b.SRMCGID,
                    SRMZCREATE = b.SRMCREATE,
                    SRMZISDELETE = b.SRMISDELETE,
                    SRMCG_LISTID = l.SRMCG_LISTID,
                    SRMPH = l.SRMPH,
                    SRMPM = l.SRMPM,
                    SRMGG = l.SRMGG,
                    SRMKMLX = l.SRMKMLX,
                    SRMFA = l.SRMFA,
                    SRMYJNYL = l.SRMYJNYL,
                    SRMREMARKS = l.SRMREMARKS,
                    SRMXHMC = l.SRMXHMC,
                    SRMCPYQ = l.SRMCPYQ,
                    SRMMJYQ = l.SRMMJYQ,
                    SRMFJ = l.SRMFJ,
                    SRMXJGYS = l.SRMXJGYS,
                    SRMXJGYS1 = l.SRMXJGYS,
                    //SRMXJGYS1 = (string[])l.SRMXJGYS.Split(',').ToArray(typeof(string)),
                    //SRMXJGYS1 = string.IsNullOrEmpty(l.SRMXJGYS) == true ? new string[] { } : l.SRMXJGYS.Split(','),
                    //SRMXJGYS1 = l.SRMXJGYS.TrimEnd(',').Split(','),
                    //SRMXJGYS1 = l.SRMXJGYS.Split(",", ystem.StringSplitOptions.None),
                    SRMZT = l.SRMZT,
                    SRMCREATE = l.SRMCREATE,
                    SRMISDELETE = l.SRMISDELETE,
                    SRMXJYXQ = l.SRMXJYXQ,
                    SRMXJYXQH = l.SRMXJYXQH


                })
                .ToPagedListAsync(input.Page, input.PageSize);

            var userlist = _Dilon.Queryable<SysUser>()
                   .Select((o) => new SysUser
                   {
                      RealName = o.RealName,
                      Account = o.Account
                   })

   .ToList();

            return output;
        }

        /// <summary>
        /// 增加采购需求
        /// </summary>
        /// <returns></returns>
        [HttpPost("/SRM/AddPurchase")]
        public async Task<string> AddPurchase(GetSrmPurchaseOutput input)
        {
            ////取项次
            //var seq = await _T100Db.Queryable<CefrbuucT>()
            //.Where(a => a.Cefrbuuc001 == input.StatementNo)
            //.MaxAsync(a => a.Cefrbuuc002) + 1;
            //初始化插入内容
            string gys = "";
            gys += input.SRMXJGYS.TrimEnd(',');
            string fj = input.SRMFJ.TrimEnd(',');
            var details = new SRMCG
            {
                SRMCGID = Guid.NewGuid().ToString("N"),
                SRMCGRID = _User.UserId,
                SRMCGRNAME =_User.RealName,
                SRMCREATE = DateTime.Now,
                SRMISDELETE = 0
            };
            var detailslist = new SRMCG_LIST
            {
                SRMCG_ID = details.SRMCGID,
                SRMCG_LISTID = Guid.NewGuid().ToString("N"),
                SRMPH = input.SRMPH,
                SRMPM = input.SRMPM,
                SRMGG = input.SRMGG,
                SRMKMLX = input.SRMKMLX,
                SRMFA = input.SRMFA,
                SRMYJNYL = input.SRMYJNYL,
                SRMREMARKS = input.SRMREMARKS,
                SRMXHMC = input.SRMXHMC,
                SRMCPYQ = input.SRMCPYQ,
                SRMMJYQ = input.SRMMJYQ,
                SRMFJ = fj,
                SRMXJYXQ = input.SRMXJYXQ,
                SRMXJYXQH = input.SRMXJYXQH,
                SRMXJGYS = gys,
                SRMZT = 0,
                SRMCREATE = DateTime.Now,
                SRMISDELETE = 0
            };
            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int cnt = await _SjDb.Insertable<SRMCG>(details).ExecuteCommandAsync();
                cnt += await _SjDb.Insertable<SRMCG_LIST>(detailslist).ExecuteCommandAsync();

                if (cnt == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
            #endregion

        }

        ///// <summary>
        ///// 增加采购需求
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("/SRM/AddPurchase")]
        //public async Task<string> AddPurchase(SrmPurchase input)
        //{
        //    ////取项次
        //    //var seq = await _T100Db.Queryable<CefrbuucT>()
        //    //.Where(a => a.Cefrbuuc001 == input.StatementNo)
        //    //.MaxAsync(a => a.Cefrbuuc002) + 1;
        //    //初始化插入内容
        //    var details = new SRMCG
        //    {
        //        SRMCGID = input.SRMCGID,
        //        SRMCGRID= _User.UserId,
        //        SRMCREATE=input.SRMCREATE,
        //        SRMISDELETE=0
        //    };
        //    #region 插入事务
        //    try
        //    {
        //        //开启事务
        //        _SjDb.Ado.BeginTran();
        //        int cnt = await _SjDb.Insertable<SRMCG>(details).ExecuteCommandAsync();
        //        for (int i = 0; i < input.srmcglist.Length; i++)
        //        {
        //            var detailslist = new SRMCG_LIST
        //            {
        //                SRMCG_ID = input.srmcglist[i].SRMCG_ID,
        //                SRMCG_LISTID = input.srmcglist[i].SRMCG_LISTID,
        //                SRMPH = input.srmcglist[i].SRMPH,
        //                SRMPM = input.srmcglist[i].SRMPM,
        //                SRMGG = input.srmcglist[i].SRMGG,
        //                SRMKMLX = input.srmcglist[i].SRMKMLX,
        //                SRMFA = input.srmcglist[i].SRMFA,
        //                SRMYJNYL = input.srmcglist[i].SRMYJNYL,
        //                SRMREMARKS = input.srmcglist[i].SRMREMARKS,
        //                SRMXHMC = input.srmcglist[i].SRMXHMC,
        //                SRMCPYQ = input.srmcglist[i].SRMCPYQ,
        //                SRMMJYQ = input.srmcglist[i].SRMMJYQ,
        //                SRMFJ = input.srmcglist[i].SRMFJ,
        //                SRMXJYXQ = input.srmcglist[i].SRMXJYXQ,
        //                SRMXJGYS = input.srmcglist[i].SRMXJGYS,
        //                SRMZT = 0,
        //                SRMCREATE = input.srmcglist[i].SRMCREATE,
        //                SRMISDELETE = 0
        //            };
        //             await _SjDb.Insertable<SRMCG_LIST>(detailslist).ExecuteCommandAsync();
        //             cnt++;
        //        }
        //        if (cnt == 0)
        //        {
        //            throw Oops.Oh($"新建任务失败！");
        //        }
        //        //提交事务
        //        _SjDb.Ado.CommitTran();
        //        return "插入成功";
        //    }
        //    catch (Exception e)
        //    {
        //        //回滚事务
        //        _SjDb.Ado.RollbackTran();
        //        throw Oops.Oh($"异常：{e.Message}");
        //    }
        //    #endregion

        //}
        #region

        ///// <summary>
        ///// 增加采购需求详情
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("/SRM/AddPurchaseList")]
        //public async Task<string> AddPurchaseList(SRMCG_LIST[] input)
        //{

        //    //初始化插入内容
        //    for (int i= 0; i < input.Length; i++){
        //        var details = new SRMCG_LIST
        //        {
        //            SRMCG_ID = input[i].SRMCG_ID,
        //            SRMCG_LISTID = input[i].SRMCG_LISTID,
        //            SRMPH = input[i].SRMPH,
        //            SRMPM = input[i].SRMPM,
        //            SRMGG = input[i].SRMGG,
        //            SRMKMLX = input[i].SRMKMLX,
        //            SRMFA = input[i].SRMFA,
        //            SRMYJNYL = input[i].SRMYJNYL,
        //            SRMREMARKS = input[i].SRMREMARKS,
        //            SRMXHMC = input[i].SRMXHMC,
        //            SRMCPYQ = input[i].SRMCPYQ,
        //            SRMMJYQ = input[i].SRMMJYQ,
        //            SRMFJ = input[i].SRMFJ,
        //            SRMXJYXQ = input[i].SRMXJYXQ,
        //            SRMXJGYS = input[i].SRMXJGYS,
        //            SRMZT = 0,
        //            SRMCREATE = input[i].SRMCREATE,
        //            SRMISDELETE = 0
        //        };
        //        try
        //        {
        //            //开启事务
        //            _SjDb.Ado.BeginTran();
        //            int cnt = await _SjDb.Insertable<SRMCG_LIST>(details).ExecuteCommandAsync();
        //            if (cnt == 0)
        //            {
        //                throw Oops.Oh($"新建任务失败！");
        //            }
        //            //提交事务
        //            _SjDb.Ado.CommitTran();

        //        }
        //        catch(Exception e)
        //        {
        //            //回滚事务
        //            _SjDb.Ado.RollbackTran();
        //            throw Oops.Oh($"异常：{e.Message}");
        //        }
        //    }

        //    return "插入成功";

        //}
        #endregion
        /// <summary>
        /// 采购需求状态更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/SubmitPurchaser")]
        public async Task<string> SubmitPurchaser(SubmitPurchaseZT input)
        {
            if ((new int[] { 1 }).Contains(input.SRMZT))
            {
                //判断单据存在
                int cnt = await _SjDb.Queryable<SRMCG_LIST>()
                    .Where(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                    .Select(a => a.SRMCG_LISTID)
                    .CountAsync();
                if (cnt == 0)
                {
                    throw Oops.Oh("任务不存在，驳回！");
                }
                else
                {
                    //提交
                    try
                    {
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<SRMCG_LIST>()
                            .SetColumns(a => a.SRMZT == input.SRMZT)
                            .Where(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                            .ExecuteCommandAsync();

                        if (count != 1)
                        {
                            throw Oops.Oh("修改状态失败！");
                        }


                        _SjDb.Ado.CommitTran();
                        return "提交成功！";
                    }
                    catch (Exception e)
                    {
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                }

            }
            else
            {
                throw Oops.Oh("状态码提交异常，驳回！");
            }

        }

        /// <summary>
        /// 采购需求更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/UpdatePurchaser")]
        public async Task<string> UpdatePurchaser(SRMCG_LIST input)
        {
            if ((new int[] { 0 }).Contains(input.SRMZT))
            {
                //判断单据存在
                int cnt = await _SjDb.Queryable<SRMCG_LIST>()
                    .Where(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                    .Select(a => a.SRMCG_LISTID)
                    .CountAsync();
                if (cnt == 0)
                {
                    throw Oops.Oh("任务不存在，驳回！");
                }
                else
                {

                    //提交
                    try
                    {
                        string gys = "";
                        gys += input.SRMXJGYS.TrimEnd(',');
                        string fj = input.SRMFJ.TrimEnd(',');

                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<SRMCG_LIST>()
                            .SetColumns(a => a.SRMPM == input.SRMPM)
                            .SetColumns(a => a.SRMPH == input.SRMPH)
                            .SetColumns(a => a.SRMGG == input.SRMGG)
                            .SetColumns(a => a.SRMKMLX == input.SRMKMLX)
                            .SetColumns(a => a.SRMFA == input.SRMFA)
                            .SetColumns(a => a.SRMYJNYL == input.SRMYJNYL)
                            .SetColumns(a => a.SRMREMARKS == input.SRMREMARKS)
                            .SetColumns(a => a.SRMXHMC == input.SRMXHMC)
                            .SetColumns(a => a.SRMCPYQ == input.SRMCPYQ)
                            .SetColumns(a => a.SRMMJYQ == input.SRMMJYQ)
                            .SetColumns(a => a.SRMFJ == fj)
                            .SetColumns(a => a.SRMXJYXQ == input.SRMXJYXQ)
                            .SetColumns(a => a.SRMXJYXQH == input.SRMXJYXQH)
                            .SetColumns(a => a.SRMXJGYS == gys)
                            //.SetColumns(a => a.SRMCREATE == input.SRMCREATE)

                            .Where(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                            .ExecuteCommandAsync();

                        if (count != 1)
                        {
                            throw Oops.Oh("修改失败！");
                        }


                        _SjDb.Ado.CommitTran();
                        return "修改成功！";
                    }
                    catch (Exception e)
                    {
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                }

            }
            else
            {
                throw Oops.Oh("状态码提交异常，驳回！");
            }

        }
        /// <summary>
        /// 采购需求删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/DeletePurchaser")]
        public async Task<string> DeletePurchaser(DeletePurchase input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<SRMCG_LIST>()
                .Where(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                .Select(a => a.SRMCG_LISTID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Updateable<SRMCG_LIST>()
                        .SetColumns(a => a.SRMISDELETE == 1)
                        .Where(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                        .ExecuteCommandAsync();

                    if (count != 1)
                    {
                        throw Oops.Oh("删除失败！");
                    }


                    _SjDb.Ado.CommitTran();
                    return "删除成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }



        }

        /// <summary>
        /// 获取采购料号对应文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("/SRM/Get111")]
        public GetProductFileOutput Get111(GetProductFileInput input)
        {
            ////获取料号对应文件清单
            //var file = _SjDb.Ado.SqlQuery<string>($@"  
            //    SELECT    FTPPATH
            //    FROM
            //        SJ1.cad_file_view 
            //    WHERE
            //        KEY='{input.Key}' and  FILENAME='{input.FileName}'
            //    UNION
            //    SELECT  FTPPATH
            //    FROM
            //        SJ1.DOC_FILE_VIEW_TEST 
            //    WHERE
            //        KEY='{input.Key}' and  FILENAME='{input.FileName}'
            //    ").FirstOrDefault();
            //var file = "upload/2023/08/09/14000019010885.step";
            string path = App.WebHostEnvironment.WebRootPath;
            var url = "http://srm.shengjiu.com:8083/upload/2023/08/09/14000019010885.step";
            string url2 = url.Substring(0, url.LastIndexOf("/upload"));
            string file = path + url.Split(url2)[1].Replace(@"/", @"\");

            //判断文件是否存在   
            if (string.IsNullOrEmpty(file))
            {
                throw Oops.Oh("文件不存在！");
            }
            //ftp连接对象
            FtpClient ftp = new FtpClient(App.Configuration["FTP:Url"], App.Configuration["FTP:Name"], App.Configuration["FTP:Pwd"]);
            //ftp连接
            ftp.Connect();



            byte[] data = null;

            ftp.DownloadBytes(out data, file);
            //判断文件是否存在
            if (data == null)
            {
                throw Oops.Oh("文件不存在！");
            }


            GetProductFileOutput output = new GetProductFileOutput();
            output.FileByte = data;
            return output;
        }
        [HttpPost("/SRM/GetStepFile")]
        public byte[] GetStepFile(string url)
        {
            string path = App.WebHostEnvironment.WebRootPath;

            // 读取二进制文件的路径
           // var url = "http://srm.shengjiu.com:8083/upload/2023/08/09/14000019010885.step";
            string url2 = url.Substring(0, url.LastIndexOf("/upload"));
            string url1 = path + url.Split(url2)[1].Replace(@"/", @"\");
            // 读取二进制文件的内容
            byte[] fileBytes = System.IO.File.ReadAllBytes(url1);
          
            // 返回二进制文件
             new FileContentResult(fileBytes, "application/octet-stream")
            {
                FileDownloadName = "file.step"
            };
            return fileBytes;
        }
       


    }
}

